
import { SDKState } from "../SDKDefine";

export default class VivoBannerAd {
    logicState = SDKState.close;
    state = SDKState.close;
    adIndex = 0;
    ids
    constructor(ids) {
        this.ids = ids;
    }
    setState(s) {
        this.state = s;
    }
    onError(err) {
        console.log('banner onError', err)
        this.setState(SDKState.loadFail)
        // this.reLoad()
    }

    onLoad() {
        console.log('banner onLoad this.logicState ', this.logicState)
        this.setState(SDKState.loadSucess)
        if (this.logicState == SDKState.open) {
        } else {
            this.hide()
        }
    }
    open(adIndex) {
        //逻辑要求开
        this.logicState = SDKState.open;
        this.state = SDKState.loading;
        this.destroy();
        this.create(adIndex)
        this.show();
    }

    close() {
        this.logicState = SDKState.close;
        if (!this.instance) {
            return
        }
        this.hide()
    }



    onResize(data) {
        console.log('banner onResize', data)
    }

    show() {
        this.state = SDKState.open
        if (this.instance) {
            this.instance.show().then(() => {
                console.log('banner广告展示完成');
                this.setState(SDKState.open)
            }).catch((err) => {
                this.setState(SDKState.close)
                console.log('banner广告展示失败', JSON.stringify(err));
            })
        }

    }

    hide() {
        this.state = SDKState.close;
        if (this.instance)
            this.instance.hide();
    }

    destroy() {
        if (this.instance) {
            this.instance.offLoad(this.onLoad.bind(this))
            this.instance.offError(this.onError.bind(this))
            this.instance.offSize(this.onResize.bind(this))
            // this.instance.destroy()
            this.instance = null;
        }
    }
    create(adIndex) {
        this.adIndex = adIndex;

        let adUnitID = this.ids[adIndex];
        let winSize = qg.getSystemInfoSync();
        this.instance = qg.createBannerAd({
            posId: adUnitID,
            style: {},
            adIntervals: 30
        })
        this.instance.onLoad(this.onLoad.bind(this))
        this.instance.onError(this.onError.bind(this))
        this.instance.onSize(this.onResize.bind(this))
    }
}